import { useAccountStore } from "@/stores/account";
import { storeToRefs } from "pinia";
/**
 * 輔助函數：解析 URL 查詢字符串為對象
 * @param {string} queryString 待解析的字符串，例如 "scene=id%3D26%26uid%3D3"
 * @returns {object} 解析後的參數對象，例如 { scene: "id=26&id=3" }
 */
export function parseUrlQuery(queryString: string) {
  if (!queryString) return {};
  const params: Record<string, any> = {};
  // 移除開頭的 '?'
  const query = queryString.startsWith('?') ? queryString.substring(1) : queryString;
  query.split('&').forEach(pair => {
    const parts = pair.split('=');
    if (parts.length === 2) {
      // 確保值被正確解碼
      params[parts[0]] = decodeURIComponent(parts[1] || '');
    }
  });
  return params;
};

/**
 * 將 JSON 對象轉換為 URL 查詢參數字符串
 * @param {object} obj - 需要轉換的 JSON 對象
 * @returns {string} 轉換後的 URL 參數字符串，例如 "key1=value1&key2=value2"
 */
export function jsonToQueryString(obj: any) {
  if (typeof obj !== 'object' || obj === null) {
    return '';
  }

  const params = [];
  for (const key in obj) {
    if (obj.hasOwnProperty(key)) {
      const value = obj[key];
      // 確保值不為 null 或 undefined
      if (value !== null && typeof value !== 'undefined') {
        const encodedKey = encodeURIComponent(key);
        const encodedValue = encodeURIComponent(value);
        params.push(`${encodedKey}=${encodedValue}`);
      }
    }
  }
  return params.join('&');
}

/**
 * 检测URL是否需要登录
 *
 * @param fullPath - URL编码 与路由地址有关，包括path、query和hash
 */
export function checkNeedLoginURL(fullPath: string) {
  const path = fullPath.split("?")[0];
  /** 游客不可访问的页面 */
  const needLoginPath: ({ pattern: RegExp } | string)[] = [
    { pattern: /^\/pages\/user.*/ },
    { pattern: /^\/pages\/recommend.*/ }, 
    "/pages/need/post", 
    "/pages/lawyer/detail"
  ];
  // 检测强制登录页面
  return needLoginPath.some((item) => {
    if (typeof item == "object" && item.pattern) {
      return item.pattern.test(path);
    }
    return path === item;
  });
}

/**
 * 跳转登录页面
 *
 * @param redirectPath - 登录成功重定向页面地址，默认当前页
 * @param loginPath - 登录路径
 */
export function toLoginPage(redirectPath?: string, loginPath = "/pages/account/login") {
  const pages = getCurrentPages<{ $page: { fullPath: string } }>();
  const fullPath = pages.length > 0 ? pages[pages.length - 1].$page.fullPath : "/";
  const url = `${loginPath}?redirect=${encodeURIComponent(redirectPath || fullPath)}`;

  // 如果在App.onLaunch调用本函数
  const navigateMethod = pages.length === 0 ? 'redirectTo' : 'navigateTo';
  if (isWeChatWeb()) {
    // @ts-ignore
    jWeixin.miniProgram[navigateMethod]({ url: `${loginPath}?redirect=${encodeURIComponent('/pages/tabbar/me')}` });
  } else {
    uni[navigateMethod]({ url });
  }
}

/**
 * 检查是否登录，用于页面按钮元素
 */
export function checkLogin () {
  const { hasLogin } = useAccountStore();
  if(!hasLogin) {
    uni.showModal({
      title:'提示',
      content:'该操作需要登录,立即登录?',
      cancelText:'稍后再说',
      confirmText:'立即登录',
      success: ({ confirm }) => {
        if(confirm) toLoginPage();
      }
    })
    return false;
  }
  return true
}


/**
 * 强制更新小程序
 * @description {@link https://developers.weixin.qq.com/community/develop/doc/000c2430d30b70251e86f0a0256c09?highLine=UpdateManager | 强制更新}
 */
export function forceUpdate() {
  const updateManager = uni.getUpdateManager();

  updateManager.onUpdateReady(() => {
    uni.showModal({
      title: "更新提示",
      content: "新版本已就绪，是否立即使用？",
      success: ({ confirm }) => {
        // 新的版本已经下载好，调用 applyUpdate 强制应用新版本并重启
        confirm && updateManager.applyUpdate();
      },
    });
  });
}

/**
 *  是否为微信浏览器加载页面
 */
export function isWeChatWeb() {
  /* #ifdef H5 */
  const ua = window.navigator.userAgent.toLowerCase();
  if (ua.match(/MicroMessenger/i)?.[0] == 'micromessenger') return true;
  /* #endif */
  return false;
}

export function handleToPage(url: string, isWebView?: boolean) {
  if(isWebView) {
    uni.navigateTo({
      url: `/pages/common/webview?url=${encodeURIComponent(url)}`
    });
  }else {
    // #ifdef H5
    uni.navigateTo({url});
    // #endif

    // #ifdef MP-WEIXIN
    const h5Urls = [
      '/pages/need/post', 
      '/pages/recommend/selected',
      '/pages/recommend/form-year',
      '/pages/recommend/form-month',
      '/pages/recommend/form-self',
    ]
    const WxUrls = [
      '/pages/activity/list', 
      '/pages/activity/detail',
      '/pages/user/activity',
      '/pages/user/collect',
      '/pages/user/settings',
    ]
    const urlAttr = url.split("?");
    if(WxUrls.includes(urlAttr[0])){
      uni.navigateTo({url});
    }else {
      // 未登录情况下，程序首次启动强制登录页面，重定向登陆页
      const { token, hasLogin } = storeToRefs(useAccountStore());
      if (!hasLogin.value && checkNeedLoginURL(url)) {
        uni.showModal({
          title:'提示',
          content:'该操作需要登录,立即登录?',
          cancelText:'稍后再说',
          confirmText:'立即登录',
          success: ({ confirm }) => {
            if(confirm) toLoginPage();
          }
        })
        return false;
      }
      const fullPath = urlAttr.length > 1 ? `${url}&token=${token.value}` : `${url}?token=${token.value}`;
      // const baseUrl = uni.getAccountInfoSync().miniProgram.envVersion == 'develop' ? 'https://test.minglvtang.com/mobile' : 'https://minglvtang.com/mobile';
      handleToPage(`https://h5.minglvtang.com${fullPath}`, true)
    }
    // #endif
  }
}

export function getImageLocalPath(url: string):Promise<string> {
  return new Promise((resolve, reject) => {
    uni.getImageInfo({
      src: url,
      success:({path})=> {
        resolve(path);
      },
      fail: ()=>{
        reject(`获取{src: ${url}}图像信息失败`)
      }
    });
  });
}


/** 打开微信客服 */
export function openServiceChat(showMessageCard = false, sendMessageTitle = "", sendMessagePath = "", sendMessageImg = "") {
  // eslint-disable-next-line no-undef
  // #ifdef MP-WEIXIN
  uni.openCustomerServiceChat({
    // 客服信息
    extInfo: {
      url: "https://work.weixin.qq.com/kfid/kfce85c9f59a3abe6aa", // 客服链接 https://work.weixin.qq.com/xxxxxxxx
    },
    corpId: "ww23a9a09e4d7cf322", // 企业ID wwed1ca4d3597eXXXX
    showMessageCard, // 是否发送小程序气泡消息
    sendMessageTitle, // 气泡消息标题
    sendMessagePath, // 气泡消息小程序路径（一定要在小程序路径后面加上“.html”，如：pages/index/index.html）
    sendMessageImg, // 气泡消息图片
    success(res) {
      console.log("客服会话打开成功", JSON.stringify(res));
    },
    fail(err) {
      uni.showToast({title: `客服会话打开失败${err}`, icon:'none'});
    },
  });
  // #endif
}
